// ignore_for_file: file_names

import 'dart:async';
import 'package:flutter_component_pay/flutter_component_pay.dart';
import 'package:fluwx/fluwx.dart';

/* 
* 微信支付
 */
class AbsWxPay {
  /// init internal object
  static final Fluwx _fluwx = Fluwx();
  static final StreamController<bool> _initStreamController = StreamController.broadcast();
  static final StreamController<bool> _notInstallStreamController = StreamController.broadcast();
  static final StreamController<bool> _openStreamController = StreamController.broadcast();
  static final StreamController<AbsPayResult> _responseStreamController = StreamController.broadcast();

  /// init answers from WeChat Pay.
  static Stream<bool> get wxInitEventHandler => _initStreamController.stream;

  /// not install wechat.
  static Stream<bool> get wxNotInstallEventHandler => _notInstallStreamController.stream;

  /// open answers from WeChat Pay.
  static Stream<bool> get wxOpenEventHandler => _openStreamController.stream;

  /// Response answers from WeChat after payment.
  static Stream<AbsPayResult> get wxResponseEventHandler => _responseStreamController.stream;

  ///
  /// 注册微信支付
  ///
  /// * [appId]
  ///
  /// * [universalLink]
  ///
  static void initWXPay({
    required String appId,
    required String universalLink,
  }) async {
    bool isSuccess = await _fluwx.registerApi(appId: appId, universalLink: universalLink);

    if (isSuccess) {
      // 监听支付响应流
      responseListener(response) {
        if (response is WeChatPaymentResponse) {
          final result = AbsPayResult(
            way: AbsPayWay.wxPay,
            code: response.errCode,
            errStr: response.errStr,
            type: response.type,
            extData: response.extData,
          );
          _responseStreamController.add(result);
        }
      }

      // 添加支付响应流
      _fluwx.addSubscriber(responseListener);
    }

    _initStreamController.add(isSuccess);
  }

  ///
  /// 调起微信支付
  ///
  /// * [paramsChannel] 支付参数模型
  ///
  static void openWxPay({
    required AbsPayParamsChannel paramsChannel,
  }) async {
    // 是否安转微信
    bool isInstalled = await _fluwx.isWeChatInstalled;

    if (!isInstalled) {
      // 未安装微信App
      _notInstallStreamController.add(true);
      return;
    }

    // 唤起微信支付
    if (paramsChannel.param != null) {
      var params = paramsChannel.param!;

      bool isSuccess = await _fluwx.pay(
        which: Payment(
          appId: params.appid ?? '',
          partnerId: params.partnerid ?? '',
          prepayId: params.prepayid ?? '',
          packageValue: params.package ?? '',
          nonceStr: params.noncestr ?? '',
          timestamp: int.parse(params.timestamp ?? '0'),
          sign: params.sign ?? '',
        ),
      );
      _openStreamController.add(isSuccess);
    } else {
      _openStreamController.add(false);
    }
  }

  ///
  /// 关闭相应StreamController流
  ///
  static void closeWxStreamControllers() {
    if (_initStreamController.hasListener) {
      _initStreamController.close();
    }
    if (_notInstallStreamController.hasListener) {
      _notInstallStreamController.close();
    }
    if (_openStreamController.hasListener) {
      _openStreamController.close();
    }
    if (_responseStreamController.hasListener) {
      _responseStreamController.close();
    }
  }
}
